/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2024 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "adc.h"
#include "i2c.h"
#include "icache.h"
#include "spi.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include "wifi.h"
#include "bsp_sht20.c"
#include "bsp_ili9341_4line.h"
#include "cJSON.h"
void USART_printf(UART_HandleTypeDef *USARTx,char *format, ...);
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
float T,H;
char temp[16];
char humi[16];
char Vbat[16];
char mode[16];
uint32_t value[2]={0};
float vbat=0;
float key=0;
int LD1=0;
int LD3=0;
int FAN=0;
int FIRE=0;
int guangshan=0;
int gate=0;
char temp1[64];
char weight[64];
char inpre[64];
char airpre[64];
char inh2[64];
char outh2[64];
int i=0;
/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void SystemPower_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
char USART5_RxBuff[1024];
uint8_t USART5_RxCounter;

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the System Power */
  SystemPower_Config();

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_ICACHE_Init();
  MX_UART5_Init();
  MX_USART1_UART_Init();
  MX_I2C1_Init();
  MX_TIM6_Init();
  MX_SPI1_Init();
  MX_TIM7_Init();
  MX_ADC1_Init();
  /* USER CODE BEGIN 2 */
  HAL_UARTEx_ReceiveToIdle_IT(&huart5, USART5_RxBuff, 1024);
	WIFI_Connect();
	HAL_TIM_Base_Start_IT(&htim6);
	HAL_TIM_Base_Start_IT(&htim7);
	ILI9341_Init();
	ILI9341_Clear(LIGHTBLUE);
	Gui_DrawFont_GBK16(65,10,RED,LIGHTBLUE,"Super NB STM32");
	Gui_DrawFont_GBK16(10,30,RED,LIGHTBLUE,"Temp:");
	Gui_DrawFont_GBK16(140,30,RED,LIGHTBLUE,"Humi:");
	Gui_DrawFont_GBK16(10,50,RED,LIGHTBLUE,"Grate:");
	Gui_DrawFont_GBK16(140,50,RED,LIGHTBLUE,"Gate:");
	Gui_DrawFont_GBK16(10,70,RED,LIGHTBLUE,"Fire:");
	Gui_DrawFont_GBK16(140,70,RED,LIGHTBLUE,"Fan:");
	Gui_DrawFont_GBK16(10,90,RED,LIGHTBLUE,"SmartLight:");
	Gui_DrawFont_GBK16(140,90,RED,LIGHTBLUE,"Vbat:");
	Gui_DrawFont_GBK16(10,110,RED,LIGHTBLUE,"MODE:");
	Gui_DrawFont_GBK16(0,130,RED,LIGHTBLUE,"------------------------------");
	Gui_DrawFont_GBK16(0,140,GREEN,LIGHTBLUE,"++++++++++++++++++++++++++++++");
	Gui_DrawFont_GBK16(0,150,RED,LIGHTBLUE,"------------------------------");
	
	Gui_DrawFont_GBK16(10,165,RED,LIGHTBLUE,"Temp:");
	Gui_DrawFont_GBK16(10,185,RED,LIGHTBLUE,"Weight:");
	Gui_DrawFont_GBK16(10,205,RED,LIGHTBLUE,"In_pre:");
	Gui_DrawFont_GBK16(10,225,RED,LIGHTBLUE,"Air_pre:");
	Gui_DrawFont_GBK16(10,245,RED,LIGHTBLUE,"In_h2:");
	Gui_DrawFont_GBK16(10,265,RED,LIGHTBLUE,"Out_h2:");
	
	
	Gui_DrawFont_GBK16(10,300,RED,LIGHTBLUE,"WIFI:");
	HAL_PWREx_EnableVddA();			//启用VDDA电压
	HAL_PWREx_EnableVddIO2();		//启用VDDIO电压
	HAL_ADCEx_Calibration_Start(&hadc1,ADC_CALIB_OFFSET,ADC_SINGLE_ENDED);  //校准单端ADC采样

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
		if(tt_flag==1)
		{
      USART_printf(&huart1, "Recive:%s\r\n", USART5_RxBuff);
			tt_flag=0;		
				
			cJSON *gen = cJSON_Parse(USART5_RxBuff);
			cJSON *data1 = cJSON_GetObjectItem(gen, "data1");

			cJSON *arr = cJSON_GetArrayItem(data1, 0);
			cJSON *arrrr1 = cJSON_GetObjectItem(arr, "tem");
			printf("tem:%d\n",arrrr1->valueint);
			sprintf(temp1,"%d",arrrr1->valueint);
			Gui_DrawFont_GBK16(52,165,RED,LIGHTBLUE,temp1);

			
			arr = cJSON_GetArrayItem(data1, 1);
			arrrr1 = cJSON_GetObjectItem(arr, "weight");
			printf("weight:%d\n",arrrr1->valueint);
			sprintf(weight,"%d",arrrr1->valueint);
			Gui_DrawFont_GBK16(70,185,RED,LIGHTBLUE,weight);
			
			
			arr = cJSON_GetArrayItem(data1, 2);
			arrrr1 = cJSON_GetObjectItem(arr, "in_pre");
			printf("in_pre:%d\n",arrrr1->valueint);
			sprintf(inpre,"%d",arrrr1->valueint);
			Gui_DrawFont_GBK16(70,205,RED,LIGHTBLUE,inpre);
			
			
			arr = cJSON_GetArrayItem(data1, 3);
			arrrr1 = cJSON_GetObjectItem(arr, "air_pre");
			printf("air_pre:%d\n",arrrr1->valueint);
			sprintf(airpre,"%d",arrrr1->valueint);
			Gui_DrawFont_GBK16(77,225,RED,LIGHTBLUE,airpre);
			
			
			arr = cJSON_GetArrayItem(data1, 4);
			arrrr1 = cJSON_GetObjectItem(arr, "in_h2");
			printf("in_h2:%d\n",arrrr1->valueint);
			sprintf(inh2,"%d",arrrr1->valueint);
			Gui_DrawFont_GBK16(60,245,RED,LIGHTBLUE,inh2);
			
			
			arr = cJSON_GetArrayItem(data1, 5);
			arrrr1 = cJSON_GetObjectItem(arr, "out_h2");
			printf("out_h2:%d\n",arrrr1->valueint);
			sprintf(outh2,"%d",arrrr1->valueint);
			Gui_DrawFont_GBK16(70,265,RED,LIGHTBLUE,outh2);
			
			arr = cJSON_GetArrayItem(data1, 6);
			arrrr1 = cJSON_GetObjectItem(arr, "ld1");
			if(i==1)
			{
				LD1=arrrr1->valueint;
			}
			printf("ld1:%d\n",arrrr1->valueint);
			
			arr = cJSON_GetArrayItem(data1, 7);
			arrrr1 = cJSON_GetObjectItem(arr, "fan");
			if(i==1)
			{
				FAN=arrrr1->valueint;
			}
			printf("fan:%d\n",arrrr1->valueint);
			
			arr = cJSON_GetArrayItem(data1, 8);
			arrrr1 = cJSON_GetObjectItem(arr, "fire");
			FIRE=arrrr1->valueint;
			printf("fire:%d\n",arrrr1->valueint);
			
			arr = cJSON_GetArrayItem(data1, 9);
			arrrr1 = cJSON_GetObjectItem(arr, "DOORRR");
			if(i==1)
			{
				gate=arrrr1->valueint;
			}
			printf("door:%d\n",arrrr1->valueint);
			
			cJSON_Delete(gen);
			
			memset(USART5_RxBuff,0,sizeof(USART5_RxBuff));
		}
		
		if(connect_flag==1)
		{
			LD3=1;
			Gui_DrawFont_GBK16(55,300,RED,LIGHTBLUE,"Connect   ");
		}
		if(connect_flag==0)
		{
			LD3=0;
			Gui_DrawFont_GBK16(55,300,RED,LIGHTBLUE,"DisConnect");
		}
	
		BSP_SHT20_GetData();
		sprintf(temp,"%.1fC",T);
		sprintf(humi,"%.1f%%",H);
		if(T>=25)
		{
			Gui_DrawFont_GBK16(55,30,RED,LIGHTBLUE,temp);
		}
		if(T<25)
		{
			Gui_DrawFont_GBK16(55,30,GREEN,LIGHTBLUE,temp);
		}
		if(H>=50)
		{
			Gui_DrawFont_GBK16(185,30,RED,LIGHTBLUE,humi);
		}
		if(H<50)
		{
			Gui_DrawFont_GBK16(185,30,GREEN,LIGHTBLUE,humi);
		}
		if(LD1==0)
		{
			HAL_GPIO_WritePin(GPIOC,GPIO_PIN_4,0);
			Gui_DrawFont_GBK16(100,90,RED,LIGHTBLUE,"OFF");
		}
		if(LD1==1)
		{
			HAL_GPIO_WritePin(GPIOC,GPIO_PIN_4,1);
			Gui_DrawFont_GBK16(100,90,GREEN,LIGHTBLUE,"ON ");
		}
		if(LD3==0)
		{
			HAL_GPIO_WritePin(GPIOC,GPIO_PIN_13,0);
		}
		if(LD3==1)
		{
			HAL_GPIO_WritePin(GPIOC,GPIO_PIN_13,1);
		}
		if(FAN==0)
		{
			HAL_GPIO_WritePin(GPIOC,GPIO_PIN_6,0);
			Gui_DrawFont_GBK16(175,70,RED,LIGHTBLUE,"OFF");
		}
		if(FAN==1)
		{
			HAL_GPIO_WritePin(GPIOC,GPIO_PIN_6,1);
			Gui_DrawFont_GBK16(175,70,GREEN,LIGHTBLUE,"ON ");
		}
		if(HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_3)==1)
		{
			FIRE=1;
			HAL_GPIO_WritePin(GPIOA,GPIO_PIN_15,1);
			Gui_DrawFont_GBK16(55,70,GREEN,LIGHTBLUE,"Appear   ");
		}
		if(HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_3)==0)
		{
			FIRE=0;
			HAL_GPIO_WritePin(GPIOA,GPIO_PIN_15,0);
			Gui_DrawFont_GBK16(55,70,RED,LIGHTBLUE,"DisAppear");
		}
		if(HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_2)==0)
		{
			guangshan=0;
			Gui_DrawFont_GBK16(60,50,GREEN,LIGHTBLUE,"Pass   ");
		}
		if(HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_2)==1)
		{
			guangshan=1;
			Gui_DrawFont_GBK16(60,50,RED,LIGHTBLUE,"UN-Pass");
		}
		if(gate==0)
		{
			Gui_DrawFont_GBK16(185,50,RED,LIGHTBLUE,"CLOSE");
		}
		if(gate==1)
		{
			Gui_DrawFont_GBK16(185,50,GREEN,LIGHTBLUE,"OPEN ");
		}
		HAL_ADC_Start(&hadc1);
		HAL_ADC_PollForConversion(&hadc1,100);
		while(!(ADC1->ISR&(1<<2)));
		value[0] = HAL_ADC_GetValue(&hadc1);
		vbat = (value[0]*3.3)/4095;
		sprintf(Vbat,"%.2f",vbat);
		Gui_DrawFont_GBK16(185,90,RED,LIGHTBLUE,Vbat);
		sprintf(mode,"%d",i);
		Gui_DrawFont_GBK16(55,110,RED,LIGHTBLUE,mode);
		while(!(ADC1->ISR&(1<<2)));
		value[1] = HAL_ADC_GetValue(&hadc1);
		key = value[1];
		HAL_ADC_Stop(&hadc1);
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  if (HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI|RCC_OSCILLATORTYPE_MSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.MSIState = RCC_MSI_ON;
  RCC_OscInitStruct.MSICalibrationValue = RCC_MSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_4;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_MSI;
  RCC_OscInitStruct.PLL.PLLMBOOST = RCC_PLLMBOOST_DIV1;
  RCC_OscInitStruct.PLL.PLLM = 1;
  RCC_OscInitStruct.PLL.PLLN = 80;
  RCC_OscInitStruct.PLL.PLLP = 2;
  RCC_OscInitStruct.PLL.PLLQ = 2;
  RCC_OscInitStruct.PLL.PLLR = 2;
  RCC_OscInitStruct.PLL.PLLRGE = RCC_PLLVCIRANGE_0;
  RCC_OscInitStruct.PLL.PLLFRACN = 0;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2
                              |RCC_CLOCKTYPE_PCLK3;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB3CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK)
  {
    Error_Handler();
  }
}

/**
  * @brief Power Configuration
  * @retval None
  */
static void SystemPower_Config(void)
{

  /*
   * Disable the internal Pull-Up in Dead Battery pins of UCPD peripheral
   */
  HAL_PWREx_DisableUCPDDeadBattery();
/* USER CODE BEGIN PWR */
/* USER CODE END PWR */
}

/* USER CODE BEGIN 4 */
void HAL_GPIO_EXTI_Falling_Callback(uint16_t GPIO_Pin)
{
	if(GPIO_Pin==GPIO_PIN_9)//key1
	{
		gate++;
		if(gate==2)
		{
			gate=0;
		}
	}
	if(GPIO_Pin==GPIO_PIN_8)//key2
	{
		FAN++;
		if(FAN==2)
		{
			FAN=0;
		}
	}
	if(GPIO_Pin==GPIO_PIN_5)//key3
	{
		LD1++;
		if(LD1==2)
		{
			LD1=0;
		}
	}
	if(GPIO_Pin==GPIO_PIN_12)//user
	{
		i++;
		if(i==2)
		{
			i=0;
		}
	}
}
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
	if(htim->Instance==TIM6)
	{
//		printf("Temp=%.1fC  Humi=%.1f%%\n",T,H);
//		if(LD1==1)
//		{
//			printf("SmartLight:ON\n");
//		}
//		if(LD1==0)
//		{
//			printf("SmartLight:OFF\n");
//		}
//		if(LD3==1)
//		{
//			printf("WIFI:Connect\n");
//		}
//		if(LD3==0)
//		{
//			printf("WIFI:DisConnect\n");
//		}
//		if(FIRE==0)
//		{
//			printf("NO FIRE\n");
//			printf("BEEP:OFF\n");
//		}
//		if(FIRE==1)
//		{
//			printf("FIRE\n");
//			printf("BEEP:ON\n");
//		}
//		if(guangshan==0)
//		{
//			printf("Grating:UN-Pass\n");
//		}
//		if(guangshan==1)
//		{
//			printf("Grating:Pass\n");
//		}
//		if(gate==0)
//		{
//			printf("Gate:CLOSE\n");
//		}
//		if(gate==1)
//		{
//			printf("Gate:OPEN\n");
//		}
//		if(FAN==0)
//		{
//			printf("FAN:CLOSE\n");
//		}
//		if(FAN==1)
//		{
//			printf("FAN:OPEN\n");
//		}
//		printf("VBAT:%.2f\n",vbat);
//		printf("key:%.0f\n",key);
  }
	if(htim->Instance==TIM7)
	{
		cJSON *root = cJSON_CreateObject();
    cJSON_AddItemToObject(root, "Device", cJSON_CreateString("wo shi nb stm32"));

		cJSON *data = cJSON_CreateArray();
    cJSON_AddItemToObject(root, "data", data);
    
		cJSON *item1 = cJSON_CreateObject();
    cJSON_AddStringToObject(item1, "temp", temp);
    cJSON_AddItemToArray(data, item1);
		
		cJSON *item2 = cJSON_CreateObject();
    cJSON_AddStringToObject(item2, "humi", humi);
    cJSON_AddItemToArray(data, item2);
    
    cJSON *item3 = cJSON_CreateObject();
    cJSON_AddNumberToObject(item3, "LD1", LD1);
    cJSON_AddItemToArray(data, item3);

    cJSON *item4 = cJSON_CreateObject();
    cJSON_AddNumberToObject(item4, "LD3", LD3);
    cJSON_AddItemToArray(data, item4);

		
		cJSON *item5 = cJSON_CreateObject();
    cJSON_AddNumberToObject(item5, "FAN", FAN);
    cJSON_AddItemToArray(data, item5);
		
		cJSON *item6 = cJSON_CreateObject();
    cJSON_AddNumberToObject(item6, "FIRE", FIRE);
    cJSON_AddItemToArray(data, item6);
		
		cJSON *item7 = cJSON_CreateObject();
    cJSON_AddStringToObject(item7, "Vbat", Vbat);
    cJSON_AddItemToArray(data, item7);
		
		cJSON *item8 = cJSON_CreateObject();
    cJSON_AddNumberToObject(item8, "Grating", guangshan);
    cJSON_AddItemToArray(data, item8);	
		
		cJSON *item9 = cJSON_CreateObject();
    cJSON_AddNumberToObject(item9, "Gate", gate);
    cJSON_AddItemToArray(data, item9);
		
		char *val = cJSON_Print(root);
    //printf("%s\n", val);
		
		cJSON_Delete(root);
		free(val);
		WIFI_SendData(val);
  }
}
void USART_printf(UART_HandleTypeDef *USARTx,char *format, ...)
{
    const char *str;
    int num;
    char buf[16];
    va_list args;
    va_start(args, format);

    while (*format != '\0')
    {
        if (*format == '\\')
        {
            format++;
            if (*format == 'r')
                HAL_UART_Transmit(USARTx, (uint8_t *)"\r", 1, HAL_MAX_DELAY);
            else if (*format == 'n')
                HAL_UART_Transmit(USARTx, (uint8_t *)"\n", 1, HAL_MAX_DELAY);
            format++;
        }
        else if (*format == '%')
        {
            format++;
            if (*format == 's')
            {
                str = va_arg(args, const char *);
                HAL_UART_Transmit(USARTx, (uint8_t *)str, strlen(str), HAL_MAX_DELAY);
            }
            else if (*format == 'd')
            {
                num = va_arg(args, int);
                snprintf(buf, sizeof(buf), "%d", num);
                HAL_UART_Transmit(USARTx, (uint8_t *)buf, strlen(buf), HAL_MAX_DELAY);
            }
            format++;
        }
        else
            HAL_UART_Transmit(USARTx, (uint8_t *)format++, 1, HAL_MAX_DELAY);
    }
    va_end(args);
}
/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
